<?php

namespace app\api\controller;

use app\admin\model\BuildingModel;
use app\admin\model\BuildingRoomModel;
use app\admin\model\ConfigValueModel;
use app\admin\model\HouseCollectModel;
use app\admin\model\HouseCommentModel;
use app\admin\model\HouseKfModel;
use app\admin\model\HouseModel;
use app\admin\model\HouseVisitModel;
use app\common\controller\Api;
use fast\Http;
use think\Db;
use think\Exception;


class House extends Api
{
    protected $noNeedLogin = ['recommend_list', 'latest_list', 'option_list', 'option_list2', 'detail', 'comments',
        'search', 'near_list', 'business_list', 'ax_list', 'user_ax_list', 'building'];
    protected $noNeedRight = ['*'];

    /**
     * @var HouseModel
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new HouseModel();
    }

    public function recommend_list()
    {
        $list = $this->getList(['is_recommend' => 1]);
        $this->success('成功', $list);
    }

    public function latest_list()
    {
        $list = $this->getList();
        $this->success('成功', $list);
    }

    public function near_list()
    {
        $house_id = $this->request->param('house_id/d', 0);
        $row = $this->model->where('id', $house_id)->find();
        $community = $row['community'] ?? 0;
        $street = $row['street'] ?? 0;
        $num = 2;
        $not_ids = [$house_id];
        // 同街道
        $list = $this->getList(['street' => $street, 'id' => ['not in', $not_ids]]);
        $result = $list->items();
        // 同社区
        if (count($result) < $num) {
            $not_ids = array_merge($not_ids, array_column($result, 'id'));
            $list = $this->getList(['community' => $community, 'id' => ['not in', $not_ids]]);
            $result = array_merge($result, $list->items());
        }

        // 浏览量
        if (count($result) < $num) {
            $this->request->get(['sort' => 'visit_num']);
            $not_ids = array_merge($not_ids, array_column($result, 'id'));
            $list = $this->getList(['id' => ['not in', $not_ids]]);
            $result = array_merge($result, $list->items());
        }
        $result = array_slice($result, 0, $num);
        $this->success('成功', $result);
    }

    public function search()
    {
        $list = $this->getList();
        $this->success('成功', $list);
    }

    public function business_list()
    {
        $where['type'] = ['in', [2, 3]];
        $list = $this->getList($where);
        $this->success('成功', $list);
    }

    public function building()
    {
        $id = $this->request->param('id/d', 0);
        $house = $this->model::get($id);
        if (empty($house)) {
            $this->error('房源不存在');
        }
        $build_id = $house->room->build_id;
        $room_ids = BuildingRoomModel::where('build_id', $build_id)->column('id');
        $where['room_id'] = ['in', $room_ids];
        $list = $this->getList($where);
        $this->success('成功', $list);
    }

    public function getList($where = [])
    {
        $where = array_merge($where, $this->getFilterWhere());
        $where['status'] = 1;
//        $where['is_finish'] = 0;

        $field = 'id,room_id,name,type,floor,area,house_type,rent,tags,images,cover';
        $page_size = $this->request->param('page_size/d', 4);
        $order = $this->getOrderWay();
        return $this->model
            ->where($where)
            ->order($order)
            ->field($field)
            ->paginate($page_size)->each(function ($item) {
                $item->append(['tags_text', 'type_text', 'house_type_text'], true);
            });
    }

    public function getFilterWhere()
    {
        $params = $this->request->param();

        $where = [];
        $kw = $this->request->param('keyword');
        if (!empty($kw)) {
            $where['name'] = ['like', '%' . $kw . '%'];
        }

        if (!empty($params['is_recommend'])) {
            $where['is_recommend'] = 1;
        }
        if (!empty($params['community'])) {
            $where['community'] = $params['community'];
        }

        if (!empty($params['street'])) {
            $where['street'] = $params['street'];
        }

        if (!empty($params['decoration'])) {
            $where['decoration'] = $params['decoration'];
        }

        if (!empty($params['house_type'])) {
            $where['house_type'] = ['in', $params['house_type']];
        }

        if (!empty($params['payment_type'])) {
            $where['payment_type'] = ['in', $params['payment_type']];
        }

        if (!empty($params['face'])) {
            $where['face'] = ['in', $params['face']];
        }

        if (!empty($params['rent'])) {
            $rent = explode('-', $params['rent']);
            if (!empty($rent[0]) && !empty($rent[1])) {
                $where['rent'] = ['between', $rent];
            } elseif (empty($rent[0]) && !empty($rent[1])) {
                $where['rent'] = ['<=', $rent[1]];
            } elseif (empty($rent[1]) && !empty($rent[0])) {
                $where['rent'] = ['>=', $rent[0]];
            }

        }

        if (!empty($params['floor'])) {
            $floor = explode('-', $params['floor']);
            if (!empty($floor[0]) && !empty($floor[1])) {
                $where['floor'] = ['between', $floor];
            } elseif (empty($floor[0]) && !empty($floor[1])) {
                $where['floor'] = ['<=', $floor[1]];
            } elseif (empty($floor[1]) && !empty($floor[0])) {
                $where['floor'] = ['>=', $floor[0]];
            }
        }

        if (!empty($params['tags'])) {
            $tags = is_string($params['tags']) ? explode(',', $params['tags']) : $params['tags'];
            foreach ($tags as $tag) {
                $where[] = Db::raw('find_in_set(' . $tag . ',tags)');
            }
        }

        $room_where = [];
        if (!empty($params['room_num'])) {
            $room_where['room_num'] = $params['room_num'];
        }
        if (!empty($params['ting_num'])) {
            $room_where['ting_num'] = $params['ting_num'];
        }
        if (!empty($params['toilet_num'])) {
            $room_where['toilet_num'] = $params['toilet_num'];
        }

        if (!empty($room_where)) {
            $where['room_id'] = ['in', function ($query) use ($room_where) {
                $query->name('building_room')->where($room_where)->field('id');
            }];
        }

        return $where;
    }

    public function getOrderWay()
    {
        //1-综合排序，2-最新发布，3-好评优先，4-价格从低到高，5-价格从高到低，
        //6-面积从小到大，7-面积从大到小，8-楼层从高到低，9-楼层从低到高
        $order_type = $this->request->param('order_type/d', 0);
        $order = [];
        switch ($order_type) {
            case 1:
                $order = ['visit_num' => 'desc'];
                break;
            case 3:
                $order = ['comment_score' => 'desc'];
                break;
            case 4:
                $order = ['rent' => 'asc'];
                break;
            case 5:
                $order = ['rent' => 'desc'];
                break;
            case 6:
                $order = ['area' => 'asc'];
                break;
            case 7:
                $order = ['area' => 'desc'];
                break;
            case 8:
                $order = ['floor' => 'desc'];
                break;
            case 9:
                $order = ['floor' => 'asc'];
                break;

        }
        return array_merge($order, ['id' => 'desc']);
    }


    public function detail_list()
    {
        $params = $this->request->param();

        $where = [];
        $user_id = $this->auth->id;
        $building_ids = BuildingModel::getUserBuildingIds($user_id);

        $type = $this->request->param('type/d');
        if (!in_array($type, [1, 2, 3])) {
            $this->error('type错误');
        }
        $status_map = [
            1 => 0,
            2 => 3,
            3 => [1, 2]
        ];
        $room_ids = BuildingRoomModel::whereIn('build_id', $building_ids)
            ->where('status', 'in', $status_map[$type])
            ->column('id');
        $where['room_id'] = ['in', $room_ids];

        $where = array_merge($where, $this->getFilterWhere());

        $where['is_finish'] = 0;
        $field = 'id,name,type,floor,area,house_type,rent,tags,images,cover';
        $page_size = $params['page_size'] ?? 10;
        $order = $this->getOrderWay();
        $list = $this->model
            ->where($where)
            ->order($order)
            ->field($field)
            ->paginate($page_size)->each(function ($item) {
                $item->append(['tags_text', 'type_text', 'house_type_text'], true);
            });

        $this->success('成功', $list);
    }

    public function option_list()
    {
        $cid = $this->request->param('cid/d', 0);
        $pid = $this->request->param('pid/d', 0);

        if ($cid == 3) {
            if (empty($pid)) {
                $pid = null;
            } else {
                $pid = (new ConfigValueModel())->where('cid', 2)
                    ->where('pid', 0)
                    ->where('option_id', $pid)
                    ->value('id');
            }
        }
        $data = (new ConfigValueModel())->getOptionList($cid, $pid);
        $this->success('success', $data);
    }

    public function option_list2()
    {
        $cid = $this->request->param('cid/d', 0);
        $pid = $this->request->param('pid/d', 0);
        if ($cid == 3) {
            if (empty($pid)) {
                $pid = null;
            } else {
                $pid = (new ConfigValueModel())->where('cid', 2)
                    ->where('pid', 0)
                    ->where('option_id', $pid)
                    ->value('id');
            }
        }

        $data = (new ConfigValueModel())->getOptionListWithIcon($cid, $pid);
        $this->success('success', $data);
    }

    public function detail()
    {
        $id = $this->request->get('id/d', 0);
        $row = $this->model->with([
            'board' => function ($query) {
                $query->field('create_time,update_time,delete_time', true);
            }, 'fixed' => function ($query) {
                $query->field('create_time,update_time,delete_time', true);
            }, 'pt' => function ($query) {
                $query->field('create_time,update_time,delete_time', true);
            }])->find($id);
        if (empty($row)) $this->error('数据不存在');
        $row->append(['house_type_text', 'payment_type_text', 'rent_type_text']);

        $room = BuildingRoomModel::where('id', $row->room_id)->find();
        $build_id = $room['build_id'] ?? 0;
        $row->room_name = $room['name'] ?? '';
        $row->building = BuildingModel::where('id', $build_id)
            ->field('id,name,address,user_id')->find()->append([], true);
        $row->room = $room;

        // 浏览量
        $row->visit_num += 1;


        $user_id = $this->auth->id ?? 0;
        // 收藏
        $collect = (new HouseCollectModel())->get([
            'house_id' => $id,
            'user_id' => $user_id
        ]);
        $row['is_collect'] = $collect ? 1 : 0;

        // 浏览
        if ($user_id) {
            $visit = (new HouseVisitModel())->get([
                'house_id' => $id,
                'user_id' => $user_id
            ]);
            if ($visit) {
                $visit->visit_time = time();
                $visit->save();
            } else {
                HouseVisitModel::create([
                    'house_id' => $id,
                    'user_id' => $user_id,
                    'visit_time' => time()
                ]);
            }
        }
        //客服
        if ($row['kf_id']) {
            $kf_mobile = HouseKfModel::where('id', $row['kf_id'])->value('mobile');
        }
        if (empty($kf_mobile)) {
            $kf_mobile = config('site.house_kf');
        }
        $row['kf_mobile'] = $kf_mobile;
        // 地址转经纬度
        $location = '';
        if ($row['address'] && empty($row['lng']) && empty($row['lat'])) {
            $map_url = 'https://restapi.amap.com/v3/geocode/geo';
            $map_data = [
                'key' => '57d200d053c41cd7d884e6b8aecae6c1',
                'address' => $row['address'],
            ];
            $map_res = Http::get($map_url, $map_data);
            $map_res = json_decode($map_res, true);
            if ($map_res['status'] == 1 && $map_res['count'] > 0) {
                $location = $map_res['geocodes'][0]['location'] ?? '';
            }
            if ($location) {
                list($lng, $lat) = explode(',', $location);
                $row->lng = $lng;
                $row->lat = $lat;
            }
        } else {
            if (!empty($row['lng']) && !empty($row['lat'])) {
                $location = $row['lng'] . ',' . $row['lat'];
            }
        }
        $row['location'] = $location;

        // 更新数据
        $row->allowField(true)->save();


        $row['title'] = $row['name'];
        $this->success('success', $row);
    }

    public function ax_list()
    {
        $page_size = $this->request->param('page_size/d', 15);
        $community = $this->request->param('community/d', 0);
        $where = [];
        $where['status'] = 1;
        $where['is_ax'] = 1;
        if ($community) {
            $where['community'] = $community;
        }
        $list = $this->model
            ->where($where)
            ->group('user_id,community')
            ->field('user_id,community,count(*) as count')
            ->paginate($page_size)
            ->each(function ($item) {
                $item->append(['community_text'], true);

                $user_info = \app\admin\model\User::find($item->user_id);
                $item->username = $user_info['username'] ?? '';
                $item->avatar = $user_info['avatar'] ?? '';
            });


        $this->success('success', $list);

    }

    public function user_ax_list()
    {
        /*$user_id = $this->request->param('user_id/d', 0);
        if ($user_id <= 0) {
            $this->error('user_id错误');
        }
        $where['user_id'] = $user_id;*/
        $where['is_ax'] = 1;
        $list = $this->getList($where);

        $this->success('success', $list);
    }


    public function comments()
    {
        $id = $this->request->param('house_id/d', 0);

        $list = (new HouseCommentModel())
            ->with(['user' => function ($query) {
                $query->withField("id,username,avatar");
            }])
            ->where('house_id', $id)
            ->where('status', 1)
            ->order('id', 'desc')
            ->paginate(15)->each(function ($item) {
                $item->user->append([], true);
            });

        $this->success('请求成功', $list);
    }

    public function add_comment()
    {
        $params = $this->request->post();
        $checkRes = $this->validate($params, [
            'house_id|房源id' => 'require',
            'type|身份类型' => 'require|in:1,2',
            'content|内容' => 'require',
            'safe|安全等级' => 'between:0,5',
            'health|卫生等级' => 'between:0,5',
            'service|服务等级' => 'between:0,5',
            'images|图片' => 'length:0,3',
        ], [
            'images.length' => '图片最多上传3张'
        ]);
        if ($checkRes !== true) {
            $this->error($checkRes);
        }
        $row = $this->model->find($params['house_id']);
        if (empty($row)) $this->error('数据不存在');

        $params['room_id'] = $row['room_id'];
        $params['user_id'] = $this->auth->id;
        $params['status'] = 1;
        $params['content'] = filter_words($params['content'] ?? '');
        $create = (new HouseCommentModel())->create($params, [
            'house_id', 'room_id', 'user_id', 'type', 'content', 'safe', 'health', 'service', 'images','status'
        ]);

        if ($create->id) {
            $safe = $params['safe'] ?? 0;
            $health = $params['health'] ?? 0;
            $service = $params['service'] ?? 0;
            $row->comment_score += ($safe + $health + $service);
            $row->save();
            $this->success('提交成功');
        }
        $this->error('提交失败');
    }

    public function add_collect()
    {
        $params = $this->request->post();
        $checkRes = $this->validate($params, [
            'house_id|房源id' => 'require',
        ]);
        if ($checkRes !== true) {
            $this->error($checkRes);
        }
        $row = $this->model->find($params['house_id']);
        if (empty($row)) $this->error('数据不存在');

        $collect = (new HouseCollectModel())->get([
            'house_id' => $params['house_id'],
            'user_id' => $this->auth->id
        ]);
        if ($collect) {
            $this->error('已收藏过了');
        }
        $params['user_id'] = $this->auth->id;

        $create = (new HouseCollectModel())->create($params, [
            'house_id', 'user_id'
        ]);

        if ($create->id) {
            $this->success('收藏成功');
        }
        $this->error('收藏失败');
    }

    public function fans_list()
    {
        $page_size = $this->request->param('page_size/d', 15);
        $kw = $this->request->param('kw');
        $user_id = $this->auth->id;
        $build_ids = BuildingModel::where('user_id', $user_id)->column('id');
        $room_ids = BuildingRoomModel::whereIn('build_id', $build_ids)->column('id');
        $house_ids = $this->model->whereIn('room_id', $room_ids)->column('id');

        $where = [];
        if (!empty($kw)) {
            $where['u.nickname'] = ['like', '%' . $kw . '%'];
        }

        $list = HouseCollectModel::alias('h')
            ->join('user u', 'h.user_id = u.id')
            ->whereIn('house_id', $house_ids)
            ->where($where)
            ->field('h.id,u.nickname,u.avatar,h.create_time')
            ->group('h.user_id')
            ->paginate($page_size)->each(function ($item) {

            });

        $this->success('success', $list);
    }

    public function cancel_collect()
    {
        $params = $this->request->post();
        $checkRes = $this->validate($params, [
            'house_id|房源id' => 'require',
        ]);
        if ($checkRes !== true) {
            $this->error($checkRes);
        }
        $row = $this->model->find($params['house_id']);
        if (empty($row)) $this->error('房源不存在');

        (new HouseCollectModel())->where([
            'house_id' => $params['house_id'],
            'user_id' => $this->auth->id
        ])->delete();

        $this->success('取消成功');

    }
}
